import json
import time

from flask import Blueprint, request
from applications.common.admin_authorization.jwtconfig import login_required, create_token
from applications.extensions.init_redis import redis_client
from applications.models import User
from applications.extensions import db
from applications.models.statusMsg import responseMessage

passport_bp = Blueprint('passport', __name__, url_prefix='/passport')

@passport_bp.post('/login')
def login_post():
    try:
        if request.method == 'POST':
            data = request.form
            user_phonenum = data.get("user_phonenum")
            password = data.get("password")
            # 验证账号密码，正确则返回token，用于后续接口权限验证
            # 之后要完成数据库的链接
            user = User.query.filter_by(user_phonenum=user_phonenum).first()
            if user.validate_password(password):
                token = create_token(user.user_role, password)
                data_key = token.encode('utf-8')
                expires = int(time.time()) + 7200
                data = "{\"user_role\":\"" + user.user_role + "\",\"user_avatar\":\"" + user.user_avatar + "\", \
                            \"user_name\":\"" + user.user_name + "\",\"user_phonenum\":\"" + user.user_phonenum + "\"}"
                p = redis_client.pipeline()
                p.set(data_key, data)
                p.expireat(data_key, expires)
                p.execute()
                return {"code": 200, "message": "success",
                        "data": {"token": token, "avatar": user.user_avatar, "user_role": user.user_role,\
                                 "user_name":user.user_name}}
            else:
                return {"code": 501, "message": "登陆失败"}

        elif request.method == 'GET':
            return {"code": 202, "message": "get is not support"}
        else:
            return {"code": 203, "message": "'not support other method'"}
    except BaseException:
        return {"code": 500, "message": "'server error'"}


@passport_bp.post('/register')
def register_post():
    try:
        req = request.form
        username = req.get('register_username')
        password = req.get('register_password')
        user_phonenum = req.get('register_phonenum')
        user_role = req.get('user_role')
        if len(db.session.query(User).filter(User.user_phonenum==user_phonenum).all()) != 0:
            return json.dumps(responseMessage(status="200", responsemsg="fail").__dict__, ensure_ascii=False)
        elif(username != '' and user_phonenum != '' and user_role != '' and user_role!= ''):
            user = User(user_name=username,user_phonenum=user_phonenum,user_role=user_role)
            user.set_password(password)
            db.session.add(user)
            db.session.commit()
            token = create_token(user.user_role, password)
            data_key = token.encode('utf-8')
            expires = int(time.time()) + 7200
            data = "{\"user_role\":\"" + user.user_role + "\",\"user_avatar\":\"" + user.user_avatar + "\",  \
                   \"user_name\":\"" + user.user_name + "\"}"
            p = redis_client.pipeline()
            p.set(data_key, data)
            p.expireat(data_key, expires)
            p.execute()
            return {"code": 200, "message": "success","data": {"token": token, "avatar": user.user_avatar,   \
                                                               "username": user.user_name}}
        else:
            raise BaseException
    except BaseException:
        db.session.rollback()
        return json.dumps(responseMessage(status="200", responsemsg="error").__dict__, ensure_ascii=False)

@passport_bp.post('/test')
# @login_required
def test():
    data = "fsdfdsf".encode('utf-8')
    expires = int(time.time()) + 7200
    data_key = "aaa"
    p = redis_client.pipeline()
    p.set(data_key, data)
    p.expireat(data_key, expires)
    p.execute()
    return "success"

@passport_bp.post('/getUserBaseInfo')
def getUserBaseInfo():
    auth=request.headers.get("Authorization")
    data = redis_client.get(auth)
    return data
